package org.ajax.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现服务器把数据转换为 JSON 字符串后，传递给客户端浏览器
 *
 * @author ZQX
 * @date 2024-11-18
 */
@WebServlet("/json.do")
public class JsonServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 操作比较麻烦 - 解决：Gson
        String json = "{\"username\":\"zs\",\"age\":18}" ;

        // 第三：响应数据
        PrintWriter out = resp.getWriter();
        out.println(json);

        out.flush();
        out.close();
    }
}
